請求轉發(RequestDispatcher),與請求重導(SendRedirect)都是Web應用程式間接訪問資源的手段,請求轉發透過HttpServletRequest執行;請求重導透過HttpServletResponse執行。相關應用場景例如login完成後重導到欲訪問的頁面或是一個請求需要多個Servlet調用才能完成時,就會透過請求轉發的方式交由下一個Servlet處理。
create DemoRequestDispatcherServlet
@WebServlet("/DemoRequestDispatcherServlet")
public class DemoRequestDispatcherServlet extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
System.out.println("====request DemoRequestDispatcherServlet====");
String username = req.getParameter("username");
System.out.println("req.getParameter(username):"+username);
//1.請求轉發是透過HttpServletRequest實現
//4. 請求資源可以是動態資源也可以是靜態資源
//req.getRequestDispatcher("ServletA").forward(req, res);
//5. 目標資源可以是WEB-INF下受保護資源
//req.getRequestDispatcher("public.html").forward(req, res);
//req.getRequestDispatcher("WEB-INF/protected.html").forward(req, res);
//6. 目標資源不可以訪問外部的資源
req.getRequestDispatcher("https://google.com.tw").forward(req, res);
}
}
create ServletA
@WebServlet("/ServletA")
public class ServletA extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res){
System.out.println("====request ServletA=====");
String username = req.getParameter("username");
System.out.println("req.getParameter(username):"+username);
}
}
創建靜態資源
創建DemoSendRedirectServlet
@WebServlet("/DemoSendRedirectServlet")
public class DemoSendRedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
System.out.println("=====DemoSendRedirectServlet=====");
String username = req.getParameter("username");
System.out.println("req.getParameter(username):"+username);
//請求重導另一種設置方式等同於SendRedirect
// res.setStatus(302);
// res.setHeader("Location", "ServletB");
//1. 請求重導是透過HttpServletResponse實現
res.sendRedirect("ServletB");
//5. 可以訪問靜態資源
//res.sendRedirect("public.html");
//6. 無法訪問WEB-INF下受保護資源
//res.sendRedirect("WEB-INF/protected.html");
//7. 目標資源可以是外部資源
//res.sendRedirect("https://www.google.com");
}
}
@WebServlet("/ServletB")
public class ServletB extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res){
System.out.println("====request ServletB=====");
String username = req.getParameter("username");
System.out.println("req.getParameter(username):"+username);
}
}